package com.itxiuyixiu.volunteer.config;

import com.itxiuyixiu.entity.enums.AuthorityType;
import com.itxiuyixiu.tools.security.handler.ApiLoginFailureHandler;
import com.itxiuyixiu.tools.security.handler.ApiLoginSuccessHandler;
import com.itxiuyixiu.tools.security.handler.ApiLogoutSuccessHandler;
import com.itxiuyixiu.volunteer.service.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @author 黄磊
 * @date 2020/5/1
 */
@Order(2)
@Configuration
public class UserSecurityConfig extends WebSecurityConfigurerAdapter {
    private final UserDetailsServiceImpl userDetialsService;
    private final ApiLoginSuccessHandler apiLoginSuccessHandler;
    private final ApiLoginFailureHandler apiLoginFailureHandler;
    private final ApiLogoutSuccessHandler apiLogoutSuccessHandler;

    public UserSecurityConfig(UserDetailsServiceImpl userDetialsService, ApiLoginSuccessHandler apiLoginSuccessHandler ,ApiLoginFailureHandler apiLoginFailureHandler , ApiLogoutSuccessHandler apiLogoutSuccessHandler) {
        this.userDetialsService = userDetialsService;
        this.apiLoginSuccessHandler = apiLoginSuccessHandler;
        this.apiLoginFailureHandler = apiLoginFailureHandler;
        this.apiLogoutSuccessHandler = apiLogoutSuccessHandler;
    }


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetialsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.antMatcher("/user/**")
                .formLogin()
                .loginPage("/user/login.html")
                .loginProcessingUrl("/user/login")
                .successHandler(apiLoginSuccessHandler)
                .failureHandler(apiLoginFailureHandler)
                .permitAll()
                .and()
                .logout().logoutUrl("/user/logout").logoutSuccessHandler(apiLogoutSuccessHandler)
                .and()
                .authorizeRequests()
                .antMatchers("/user/register" ,"/user/register/email" ,"/user/password").permitAll()
                .anyRequest().hasAuthority(AuthorityType.ROLE_USER)
                .and().httpBasic().and().csrf().disable().cors();
    }
}
